<template>
  <div class="card" style="height: 80vh">
    <div class="font-semibold text-xl mb-4">实例</div>
    <div class="grid grid-cols-3 gap-4">
      <div class="flex items-center col-3">
        <label class="w-36">全局搜索</label>
        <InputText v-model="queryFormState._full" class="w-full"/>
      </div>
      <div v-if="expandedSearch" v-for="col in field.filter(item => !item.meta.hidden)"
           class="flex items-center col-3">
        <label class="w-36 text-center">{{ col.name }}</label>
        <InputText v-model="queryFormState[col.field_id]" class=""/>
        <div class="w-32 ml-3">
          <Checkbox v-model="queryFormState[col.field_id + '_like']" :value="true"/>
          <label> 精确 </label>
        </div>
      </div>
      <div class="">
        <Button class='ml-2' @click="querySubmit"
                label="查询"></Button>
        <Button
            @click="resetQuery"
            class='ml-2'
            severity="secondary"
            label="重置"></Button>
        <Button class='ml-2' :label="expandedSearch === true ? '收起' : '展开搜索'"
                :icon="'pi ' + (expandedSearch === true ? 'pi-chevron-up' : 'pi-chevron-down')"
                severity="secondary" text
                @click="expandedSearch = !expandedSearch"/>
      </div>
    </div>
    <div class="flex justify-end">
      <Button class="mr-2" type="button" icon="pi pi-plus-circle" label="新建"
              @click="() => {resetCreate();visible.instanceCreate = true} "/>
      <Button class="mr-2" icon="pi pi-file-import" @click="() => visible.instanceImport = true"
              label="导入"></Button>
      <Button icon="pi pi-sliders-v" severity="secondary" outlined
              @click="columnsToggle"/>
    </div>
    <div class="h-1rem"></div>
    <DataTable :value="instanceList" :rows="10" dataKey="id" :loading="instanceLoading" scrollable
               scrollHeight="55vh">
      <Column v-for="col in field.filter(item => !item.meta.hidden)" :key="col.id" :field="col.field_id"
              :header="col.name"></Column>
      <Column field="action" header="操作" style="width: 100px">
        <template #body="slotProps">
          <i class="pi pi-pencil" @click="() => openEditor(slotProps.data)"></i>
          <i class="pi pi-trash ml-3" @click="() => requireConfirmation(slotProps.data)"></i>
        </template>
      </Column>
    </DataTable>

    <Paginator
        :page="queryState.page"
        :rows="queryState.rows"
        :totalRecords="total"
        :rowsPerPageOptions="[10, 20, 30, 50, 100]"
        template="FirstPageLink PrevPageLink PageLinks  NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
        currentPageReportTemplate="{totalRecords}条"
        @page="(PageState) => {queryState.page = PageState.page;queryState.rows = PageState.rows;instanceRun(queryState)}">
    </Paginator>
  </div>

  <Dialog
      modal
      style="width: 40rem"
      header="新增实例数据"
      v-model:visible="visible.instanceCreate"
  >
    <!--<Form :validation-schema="instanceSchema" :initial-values="initialValues" @submit="instanceSubmit">-->
    <div class="grid">
      <div v-for="field in field" class="col-6">
        <label class="font-semibold text-right h-2rem">{{ field.name }}</label>
        <div class="mt-2">
          <!--<Field :name="field.field_id" v-slot="{ handleChange, handleBlur, value }">-->
          <InputText v-model="createFormState[field.field_id]" class="flex-auto w-full"/>
          <!--</Field>-->
        </div>
      </div>
    </div>

    <div class="flex justify-content-end gap-2 mt-6">
      <Button type="button" label="取消" severity="secondary"
              @click="visible.instanceCreate = false"></Button>
      <Button label="保存" @click="instanceSubmit"></Button>
    </div>
    <!--</Form>-->
  </Dialog>
  <Dialog
      modal
      :style="{ width: '32rem' }"
      header="导入实例数据"
      v-model:visible="visible.instanceImport"
  >
    <div class="flex align-items-center gap-3 mb-5">
      <label class="font-semibold w-6rem">类型</label>
      <div>
        <label> {{ instanceDetail.name }} </label>
      </div>
    </div>
    <div class="flex align-items-center gap-3 mb-5">
      <label class="font-semibold w-6rem">选择唯一字段</label>
      <div>
        <Select v-model="instanceImportFormState.unique" :options="field" optionValue="field_id"
                optionLabel="name"
                placeholder="选择导入的唯一字段"
                class="w-full md:w-56"/>
      </div>
    </div>
    <div class="flex align-items-center gap-3 mb-5">
      <label class="font-semibold w-6rem">选择xlsx文件</label>
      <div>
        <FileUpload
            customUpload
            chooseLabel="导入实例"
            class="m-2"
            mode="basic"
            name="file"
            :withCredentials="true"
            ref="fileupload"
        />
      </div>
    </div>
    <div class="flex justify-content-end gap-2 mt-6">
      <Button type="button" label="取消" severity="secondary" @click="visible.instanceImport = false"></Button>
      <Button type="submit" @click="upload" :loading="instanceImportLoading" label="导入"></Button>
    </div>
  </Dialog>
  <Menu ref="columnsMenu" :model="fieldRef" :popup="true">
    <template #item="{ item, props }">
      <a v-ripple class="flex items-center" v-bind="props.action" @click="(e) => e.stopPropagation()">
        <span v-if="item.meta.hidden" class="pi pi-eye-slash" @click="(e) => field_update(item, false)"/>
        <span v-else class="pi pi-eye" @click="(e) => field_update(item, true)"/>
        <span>{{ item.name }}</span>
      </a>
    </template>
  </Menu>
  <ConfirmDialog></ConfirmDialog>
</template>
<script setup>
import IconField from 'primevue/iconfield';
import InputIcon from 'primevue/inputicon';
import ConfirmDialog from 'primevue/confirmdialog';
import {cloneDeep} from 'lodash-es';
import {reactive, ref, computed, watch} from "vue";
import {useRequest} from 'vue-request';
import {
  ApiInstanceList,
  ApiInstanceCreate, ApiInstanceImportExcel,
  ApiFieldUpdate, ApiInstancelDetail, ApiInstanceUpdate, ApiInstanceDelete, ApiSchemalDetail
} from "@/api/cmdb.js";
import {useToast} from "primevue/usetoast";
import {useRoute} from "vue-router";
import router from "@/router.js";
import {useConfirm} from "primevue/useconfirm";
import Select from 'primevue/select';
import Checkbox from 'primevue/checkbox';

const confirm = useConfirm();
const toast = useToast();
const route = useRoute();
const schema_id = route.query.schema_id

const columnsMenu = ref();
const visible = reactive({
  instanceCreate: false,
  instanceImport: false,
  querySave: false,
  import: false
})


const instanceImportFormState = reactive({})

const expandedSearch = ref(false)
const queryState = reactive({
  schema_id: schema_id,
  page: 0,
  rows: 10,
  query: []
})
const queryFormState = reactive({})
const createFormState = reactive({})
const fieldRef = ref([])
const fileupload = ref();
const instanceImportLoading = ref(false);
const uploadLoading = ref(false)


const fileList = []

const {
  data: schemaData,
  loading: schemaLoading,
} = useRequest(ApiSchemalDetail, {
  defaultParams: [schema_id],
})

const {
  data: instanceData,
  loading: instanceLoading,
  run: instanceRun,
  refresh: instanceRefresh
} = useRequest(ApiInstanceList, {
  defaultParams: [queryState],
})

const instanceList = computed(() => instanceData.value?.data.list || []);
const instanceDetail = computed(() => schemaData.value?.data.detail || []);
const field = computed(() => instanceData.value?.data.field || []);
const total = computed(() => instanceData.value?.data.total || []);


const querySave = async () => {
  visible.querySave = true
}

const instanceSchema = ref(null);

watch(field, (newField) => {
  if (newField) {
    fieldRef.value = instanceData.value.data.field
  }
});


const instanceSubmit = async () => {
  let query = []
  let result;
  if (createFormState.instance_id) {
    result = await ApiInstanceUpdate({instance_id: createFormState.instance_id, data: createFormState})
  } else {
    result = await ApiInstanceCreate({schema_id: schema_id, data: createFormState})
  }
  if (result.code === 0) {
    toast.add({severity: 'success', summary: '成功', detail: result.msg, life: 3000});
    visible.instanceCreate = false
    instanceRefresh()
  } else {
    toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
  }
}

const querySubmit = async () => {
  // 拼接查询参数提交给后端
  queryState.query = []
  Object.entries(queryFormState).forEach(([key, value]) => {
    if (!key.endsWith('_like')) {
      let comparison = 'like'
      const like_key = key + '_like'
      if (like_key in queryFormState && queryFormState[like_key][0] === true) {
        comparison = '='
      }
      queryState.query.push({
        field: key,
        value: value,
        comparison: comparison
      })
    }
  });
  await instanceRun({...queryState})
}

const resetQuery = () => {
  queryState.query = [];
  Object.keys(queryFormState).forEach(key => {
    delete queryFormState[key];
  });
  instanceRun(queryState)
}


const resetCreate = () => {
  Object.keys(createFormState).forEach(key => {
    delete createFormState[key];
  });
}

const swiftRemoveSubmit = async (name) => {
  const result = await ApiModelSwiftRemove({model: 'host', swift_name: name})
  if (result.code === 0) {
    message.success(result.msg)
    modelRun()
  } else {
    message.error(result.msg)
  }
}


const upload = async () => {
  instanceImportLoading.value = true
  const formData = new FormData();
  formData.append('schema_id', schema_id);
  formData.append('unique', instanceImportFormState.unique);
  formData.append('file', fileupload.value.files[0]);
  const result = await ApiInstanceImportExcel(formData)
  if (result.code === 0) {
    toast.add({severity: 'success', summary: '成功', detail: result.msg, life: 3000});
    visible.instanceImport = false
  } else {
    toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
  }
  instanceImportLoading.value = false

};

const columnsToggle = (event) => {
  columnsMenu.value.show(event);
};

const field_update = async (data, hidden) => {
  data.meta.hidden = hidden

  const result = await ApiFieldUpdate({id: data.id, meta: data.meta})
  if (result.code === 0) {
    instanceRefresh()
  } else {
    toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
  }
}

const openEditor = async (data) => {
  await resetCreate()
  const result = await ApiInstancelDetail(data.instance_id)
  if (result.code === 0) {
    for (const [key, value] of Object.entries(result.data.detail)) {
      createFormState[key] = value
    }
    visible.instanceCreate = true
  } else {
    toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
  }
}


const requireConfirmation = (data) => {
  confirm.require({
    message: '确定要删除该实例数据吗？',
    header: '删除提示',
    icon: 'pi pi-info-circle',
    rejectLabel: '取消',
    rejectProps: {
      label: '取消',
      severity: 'secondary',
      outlined: true
    },
    acceptProps: {
      label: '删除',
      severity: 'danger'
    },
    accept: async () => {
      const result = await ApiInstanceDelete(data.instance_id)
      if (result.code === 0) {
        toast.add({severity: 'success', summary: '成功', detail: result.msg, life: 3000});
        instanceRefresh()
      } else {
        toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
      }

    },
  });
};

</script>